import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/components/Login/login'
import { getToken } from '@/utils/auth'
import { initWebsocket } from '@/api/websocket'
import store from "@/store";
Vue.use(VueRouter)

const router = new VueRouter({
    mode: 'history',
    routes: [
        {
            path: '/login',
            component: Login,
            meta:{ title: '登陆'}
        },
        {
            path: '/active',
            component: () => import('@/views/Active'),
            meta:{ title: '登陆'}
        },
        {
            path: '/gitee/callback',
            component: () => import('@/views/OAuth2Login'),
            meta:{ title: '码云登陆'}
        },
        {
            path: '/',
            component: () => import('@/views/Home'),
            meta: { title: '首页' },
        },
        {
            path: '/blog/:bId',
            name: 'Blog',
            component: () => import('@/views/Blog'),
        },
        {
            path: '/:type/:id',
            name: 'CategoryOrTag',
            component: () => import('@/views/CategoryOrTag'),
            meta: {title: '文章分类'}
        },
        {
            path: '/message',
            name: 'Message',
            component: () => import('@/views/Message'),
            meta: {title: '留言'}
        },
        { path: '*', name:'404',component: () => import('@/views/404') },
    ]
})

router.beforeEach((to, from, next) => {
    let token = getToken();
    if (token){  //登陆
        if (!store.state.user.id){  //刷新页面
            //重新获取数据
            store.dispatch('getUserInfo').then(res => {
                initWebsocket(res.id)
            })

        }
    }
    next()
})

//解决vue路由重复导航错误
//获取原型对象上的push函数
const originalPush = VueRouter.prototype.push
//修改原型对象中的push方法
VueRouter.prototype.push = function push(location) {
    return originalPush.call(this, location).catch(err => err)
}

export default router
